# -*- encoding:utf-8 -*-
import toolapi
import base64
from memory_pic import favicon_ico
import sys
import time
import datetime
from UI import Ui_MainWindow
from PyQt5.QtCore import QThread, pyqtSignal, QMutex, QTimer
from tkinter import messagebox
from os import system
from PyQt5 import QtCore, QtGui, QtWidgets

class Thread_login(QThread):#线程_登录校园网
    value = pyqtSignal(str)
    def __init__(self):
        super(Thread_login,self).__init__()
        self.mutex = QMutex()
        self.url1 = 'https://www.baidu.com'
        self.is_running = True

    def stop(self):
        self.is_running = False
        self.wait()

    #运行（入口）
    def run(self):
        while self.is_running:
            # 线程锁ON
            self.mutex.lock()
            account = toolapi.account_conf.account.obtainini(self)
            if account == '配置信息不存在':
                self.value.emit(account)
            else:
                userid = account[0]
                password = account[1]
                url = account[2]
                if not toolapi.net.verify(url=self.url1):#判断是否联网
                    if toolapi.net.verify(url=url):#判断是否在校园网范围内
                        result = toolapi.net.login(url=url, userid=userid, password=password)
                        self.value.emit(result)
                    else:
                        self.value.emit('未在校园网范围内')
                else:
                    self.value.emit('已连接互联网')
            self.value.emit(str(datetime.datetime.now()))
            # 线程锁off
            self.mutex.unlock()

class Thread_logout(QThread):#线程_登出校园网
    value1 = pyqtSignal(str)
    def __init__(self):
        super(Thread_logout,self).__init__()
        self.mutex = QMutex()
        self.url1 = 'https://www.baidu.com'
        self.is_running = True

    def stop(self):
        self.is_running = False
        self.wait()

    #运行（入口）
    def run(self):
        while self.is_running:
            # 线程锁ON
            self.mutex.lock()
            account = toolapi.account_conf.account.obtainini(self)
            if account == '配置信息不存在':
                self.value1.emit(account)
            elif len(account) < 4:
                self.value1.emit("未获取userindex，请先运行一次程序")
            else:
                url = account[2]
                userindex = account[3]
                if  toolapi.net.verify(url=self.url1):#判断是否联网
                    if toolapi.net.verify(url=url):#判断是否在校园网范围内
                        result = toolapi.net.logout(url=url, userindex=userindex)
                        self.value1.emit(result)
                    else:
                        self.value1.emit('未在校园网范围内')
                else:
                    self.value1.emit('已断开互联网')
            self.value1.emit(str(datetime.datetime.now()))
            # 线程锁off
            self.mutex.unlock()

class Thread_reconnection(QThread):#线程_自动重连
    value2 = pyqtSignal(str)

    def __init__(self):
        super(Thread_reconnection, self).__init__()
        self.mutex = QMutex()
        self.url1 = 'https://www.baidu.com'

    def run(self):
        self.value2.emit('启动自动断连')
        self.value2.emit(str(datetime.datetime.now()))
        account1 = toolapi.account_conf.account.obtainini(self)
        if account1 == '配置信息不存在':
            self.value2.emit(account1)
        else:
            userid = account1[0]
            password = account1[1]
            url = account1[2]
            while (True):
                # 线程锁ON
                self.mutex.lock()
                if not toolapi.net.verify(url=self.url1):#判断是否联网
                    if toolapi.net.verify(url=url):#判断是否在校园网范围内
                        result = toolapi.net.login(url=url, userid=userid, password=password)
                        self.value2.emit(result)
                        self.value2.emit(str(datetime.datetime.now()))
                    # 线程锁off
                self.mutex.unlock()
                time.sleep(5)

class Thread_powerpage(QThread):#线程_电源
    value3 = pyqtSignal(str)
    value_a = pyqtSignal(int)
    def __init__(self):
        super(Thread_powerpage, self).__init__()
        self.mutex = QMutex()

    def run(self):
        a = 0
        self.value3.emit('启动电源监管')
        self.value3.emit(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())))
        while True:
            #线程锁ON
            self.mutex.lock()
            power = toolapi.power.inspect_power()
            percent = toolapi.power.check_battery()
            now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
            if not power:
                options = {"type": "okcancel"}
                system("shutdown -s -t  10 ")
                result = messagebox.showwarning("警告",
                                                "电源已断开\n当前电量：{0}\n当前时间:{1}\n10秒后关机".format(percent,now_time),
                                                **options)
                if result == 'cancel':
                    system('shutdown -a')
            self.value3.emit(str(power))
            self.value3.emit(str(now_time))
            a += 1
            self.value_a.emit(a)
            if a == 10:
                a = 0
            time.sleep(1)
            # 线程锁off
            self.mutex.unlock()

class Thread_shutdown(QThread):#线程_关机
    value4 = pyqtSignal(str)
    def __init__(self):
        super(Thread_shutdown,self).__init__()
        self.mutex = QMutex()
        self.work2 = Thread_logout

    #运行（入口）
    def run(self):
        # 线程锁ON
        self.mutex.lock()
        self.work2 = Thread_logout()
        self.work2.start()# 先登出校园网
        toolapi.cmdrun.shutdown()  # 后关机
        # 线程锁off
        self.mutex.unlock()


class Thread_opennote(QThread):#线程_打开笔记
    def __init__(self):
        super(Thread_opennote,self).__init__()
        self.mutex = QMutex()

    #运行（入口）
    def run(self):
        # 线程锁ON
        self.mutex.lock()
        toolapi.cmdrun.Samsung_Notes()
        # 线程锁off
        self.mutex.unlock()

class my_mainwindow(Ui_MainWindow):
    def __init__(self, mainWindow):
        super().__init__()
        self.setupUi(mainWindow)
        self.initUi()
        self.url1 = 'https://www.baidu.com'

    def initUi(self):
        self.work1 = Thread_login()
        self.work2 = Thread_logout()
        self.work3 = Thread_reconnection()
        self.work4 = Thread_powerpage()
        # self.work5 = Thread_shutdown()
        self.work6 = Thread_opennote()
        self.run_pushButton.clicked.connect(self.run_btn)
        self.exit_pushButton.clicked.connect(self.exit_btn)
        self.shutdown_pushButton.clicked.connect(self.std_btn)
        self.note_pushButton.clicked.connect(self.note_btn)
        self.save_pushButton.clicked.connect(self.save_btn)
        self.clean_pushButton.clicked.connect(self.clean_btn)
        self.break_pushButton.clicked.connect(self.break_btn)
        self.Reconnection_checkBox.clicked.connect(self.reconnection)
        self.work3.value2.connect(self.textBrowser.append)
        self.work3.start()
        # self.powerup_checkBox.stateChanged.connect(self.powerup)
        self.powermanage_checkBox.clicked.connect(self.powermanage)
        self.work4.value3.connect(self.textBrowser_3.append)
        self.powermanage()
        self.work4.start()

    def run_btn(self):#运行
        self.run_pushButton.setEnabled(False)
        QTimer.singleShot(1000, lambda:self.run_pushButton.setEnabled(True))#限制按钮点击频率，1s一次
        self.work1 = Thread_login()
        self.work1.value.connect(self.showbrw1)
        self.work1.start()


    def exit_btn(self):#退出
        self.exit_pushButton.setEnabled(False)
        QTimer.singleShot(1000, lambda:self.exit_pushButton.setEnabled(True))
        self.work2 = Thread_logout()
        self.work2.value1.connect(self.showbrw1_1)
        self.work2.start()

    def showbrw1(self,msg):#文本框显示
        self.textBrowser.append(msg)
        self.work1.stop()

    def showbrw1_1(self, msg):#文本框显示
        self.textBrowser.append(msg)
        self.work2.stop()

    def std_btn(self):
        self.work3.terminate()
        self.Reconnection_checkBox.setChecked(False)
        self.shutdown_pushButton.setEnabled(False)
        QTimer.singleShot(1000, lambda:self.shutdown_pushButton.setEnabled(True))
        self.exit_btn()
        toolapi.cmdrun.shutdown()

    def note_btn(self):
        self.note_pushButton.setEnabled(False)
        QTimer.singleShot(1000, lambda:self.note_pushButton.setEnabled(True))
        self.work6 = Thread_opennote()
        self.work6.start()


    def save_btn(self):
        usename = self.account_lineEdit_2.text()
        password = self.password_lineEdit_2.text()
        url = self.compus_url_lineEdit_2.text()
        toolapi.account_conf.account(usename, password, url).setini()
        self.textBrowser_2.append(usename)
        self.textBrowser_2.append(password)
        self.textBrowser_2.append(url)

    def clean_btn(self):
        toolapi.account_conf.account.cleanini(self)
        self.textBrowser_2.clear()

    def break_btn(self):
        self.textBrowser_2.clear()
        account = toolapi.account_conf.account.obtainini(self)
        username = account[0]
        password = account[1]
        url = account[2]
        self.textBrowser_2.append(username)
        self.textBrowser_2.append(password)
        self.textBrowser_2.append(url)
        if len(account) >= 4:
            userindex = account[3]
            self.textBrowser_2.append(userindex)

    def reconnection(self):
        if self.Reconnection_checkBox.isChecked():
            self.work3 = Thread_reconnection()
            self.work3.value2.connect(self.textBrowser.append)
            self.work3.start()
        else:
            self.work3.terminate()
            self.textBrowser.append('结束自动断连')
            self.textBrowser.append(str(datetime.datetime.now()))

    def powermanage(self):
        if self.powermanage_checkBox.isChecked():
            self.work4 = Thread_powerpage()
            self.work4.value3.connect(self.textBrowser_3.append)
            self.work4.value_a.connect(self.step)
            self.work4.start()
        else:
            self.work4.terminate()
            self.textBrowser_3.append('关闭电源监管')
            self.textBrowser_3.append(str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())))

    def step(self,data):
        if data == 10:
            self.textBrowser_3.clear()

class TrayIcon(QtWidgets.QSystemTrayIcon):
    def __init__(self, MainWindow, parent=None):
        super(TrayIcon, self).__init__(parent)
        self.ui = MainWindow
        self.createMenu()

    def createMenu(self):
        self.menu = QtWidgets.QMenu()
        self.showAction1 = QtWidgets.QAction("显示主窗口", self, triggered=self.show_window)
        self.showAction2 = QtWidgets.QAction("关机", self, triggered=self.shutdown)
        self.quitAction = QtWidgets.QAction("退出", self,     triggered=self.quit)

        self.menu.addAction(self.showAction1)
        self.menu.addAction(self.showAction2)
        self.menu.addAction(self.quitAction)
        self.setContextMenu(self.menu)

        # 设置图标
        Logo = QtGui.QPixmap()
        Logo.loadFromData(base64.b64decode(favicon_ico))
        icon = QtGui.QIcon()
        icon.addPixmap(Logo, QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setIcon(icon)
        self.icon = self.MessageIcon()

        # 把鼠标点击图标的信号和槽连接
        self.activated.connect(self.onIconClicked)

    def shutdown(self):
        Thread_shutdown.start()

    def show_window(self):
        # 若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
        self.ui.showNormal()
        self.ui.activateWindow()

    def quit(self):
        QtWidgets.qApp.quit()

    # 鼠标点击icon传递的信号会带有一个整形的值，1是表示单击右键，2是双击，3是单击左键，4是用鼠标中键点击
    def onIconClicked(self, reason):
        if reason == 2 or reason == 3:
            # self.showMessage("Message", "skr at here", self.icon)
            if self.ui.isMinimized() or not self.ui.isVisible():
                # 若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
                self.ui.showNormal()
                self.ui.activateWindow()
                self.ui.setWindowFlags(QtCore.Qt.Window)
                self.ui.show()
            else:
                self.ui.close()
